import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 参数方程下弧长计算
def arc_length_parametric(x, y, x_prime, y_prime, alpha, beta):
    """
    计算参数方程下曲线的弧长
    x, y: 参数函数
    x_prime, y_prime: 参数的导数
    alpha, beta: 参数区间
    """
    def integrand(t):
        return np.sqrt(x_prime(t)**2 + y_prime(t)**2)
    
    length, error = integrate.quad(integrand, alpha, beta)
    return length, error

# 示例：摆线一拱的长度
a = 1  # 摆线参数

def x_cycloid(theta):
    return a * (theta - np.sin(theta))

def y_cycloid(theta):
    return a * (1 - np.cos(theta))

def x_prime_cycloid(theta):
    return a * (1 - np.cos(theta))

def y_prime_cycloid(theta):
    return a * np.sin(theta)

length_cycloid, error_cycloid = arc_length_parametric(
    x_cycloid, y_cycloid, x_prime_cycloid, y_prime_cycloid, 0, 2*np.pi)

print(f"摆线一拱的长度: {length_cycloid:.6f} (理论值: {8*a:.6f})")

# 可视化摆线
theta = np.linspace(0, 2*np.pi, 100)
x_vals = x_cycloid(theta)
y_vals = y_cycloid(theta)

plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, 'r-', linewidth=2, label='摆线')
plt.xlabel('x')
plt.ylabel('y')
plt.title('摆线一拱')
plt.grid(True)
plt.axis('equal')
plt.legend()

# 标注弧长
plt.text(3, 1.5, f'弧长 L = {length_cycloid:.4f}', fontsize=12, 
         bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.7))

plt.show()